<?php
/*
 * @Author: SanQian
 * @Date: 2021-09-06 17:18:02
 * @LastEditTime: 2021-09-07 11:11:12
 * @LastEditors: SanQian
 * @Description:
 * @FilePath: /tools_php_kuaidi100/src/Kuaidi100Basic.php
 *
 */

namespace Zhaohangyang\ToolsPhpKuaidi100;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ServerException;

class Kuaidi100Basic
{
    public $apiClient;

    public $config = [
    ];

    public $standardConfig = [
        // 客户授权key
        'key'      => '',
        // 查询公司编号
        'customer' => '',
        // 接口地址
        'api_url'  => '',
    ];

    public function __construct($config)
    {
        $this->verifyConfig($config);

        $this->config    = $config;
        $this->apiClient = $this->setApiClient($this->config['api_url']);
    }

    public function verifyConfig($config)
    {
        $diff_keys = array_diff_key($this->standardConfig, $config);

        if (!empty($diff_keys)) {
            throw new \Exception("配置参数不全，缺少:" . implode(",", array_keys($diff_keys)), 1);
        }
    }

    public function setApiClient($api_url = '')
    {
        $this->apiClient = new Client([
            'base_uri'    => $api_url ?: $this->config['api_url'],
            'timeout'     => 600,
            'verify'      => false,
            'http_errors' => false,
        ]);

        return $this->apiClient;
    }

    public function getApiClient($api_url)
    {
        return $this->apiClient ?: $this->setApiClient($api_url);
    }

    /**
     * 发送请求，并返回结果
     *
     * @param \GuzzleHttp\Psr7\Request $request
     * @param string $interface_type
     * @return void
     */
    public function requestJsonSync(\GuzzleHttp\Psr7\Request $request)
    {
        try {
            $response = $this->apiClient->send($request);
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

        return json_decode($response->getBody(), true);
    }

    public function getSign($param)
    {
        $sign = md5(json_encode($param) . $this->config['key'] . $this->config['customer']);
        return strtoupper($sign);
    }

    public function getPostData($param = [])
    {
        $post_data = [
            'customer' => $this->config['customer'],
            'param'    => json_encode($param),
            'sign'     => $this->getSign($param),
        ];
        return http_build_query($post_data);
    }

    public function curlPost($url, $param)
    {
        $post_data = $this->getPostData($param);
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data   = str_replace("\"", '"', $result);

        return json_decode($data);
    }
}
